package nl.hva.three2learn.dao;

import java.util.List;

import nl.hva.three2learn.model.Category;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public final class CategoryDaoImpl implements CategoryDao {

	@Autowired
	private SessionFactory sessionFactory;
	
	@Override
	public Category findById(long categoryId) {
		
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		
		Query q = session.createQuery("from Category c where c.id = :id");
		q.setParameter("id", categoryId);
		
		Object result = q.uniqueResult();
		
		session.getTransaction().commit();
		
		if (result == null)
			return null;
		
		return (Category) result;
	}

	@Override
	public List<Category> findAllCategories() {
		
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		
		Query q = session.createQuery("from Category");
		
		List<Category> categories = q.list();
		
		session.getTransaction().commit();
		
		return categories;
	}

	@Override
	public void save(Category category) {
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		session.saveOrUpdate(category);
		session.getTransaction().commit();
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public void delete(Category category) {
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		session.delete(category);
		session.getTransaction().commit();
	}
}